/*
 * 文件名：DesignChangeController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月27日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.DesignChangeAssist;
import top.infopub.mgr.ic.domain.DesignChangeDomain;
import top.infopub.mgr.ic.service.DesignChangeService;
import top.infopub.mgr.ic.service.DesignExamService;
import top.infopub.mgr.ic.vo.DesignChangeVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.ic.DesignChangeAtt;
import top.infopub.model.ic.DesignChangeDetail;
import top.infopub.model.ic.DesignExam;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 设计方案变更
 * @author WuZhiyang
 * @version 2020年3月27日
 * @see DesignChangeController
 * @since
 */
@Controller
@RequestMapping("/designChange")
public class DesignChangeController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private DesignExamService designExamService;

    @Autowired
    private DesignChangeService designChangeService;

    /**
     * 设计方案变更列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-designChange-list";
    }

    /**
     * 设计方案变更列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<DesignChangeDomain> queryDataByCondition(DesignChangeVo designChangeVo,
                                                          ParamPage paramPage) {
        Page<DesignChangeDomain> page = new Page<DesignChangeDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (designChangeVo.getEndDate() != null) {
            designChangeVo.setEndDate(DateUtils.addDays(designChangeVo.getEndDate(), 1));
        }
        page = designChangeService.selectByDomainWhere(page, designChangeVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 设计方案变更-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<DesignChangeDomain> queryMyCheckDataByCondition(DesignChangeVo designChangeVo,
                                                                 ParamPage paramPage) {
        Page<DesignChangeDomain> page = new Page<DesignChangeDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (designChangeVo.getEndDate() != null) {
            designChangeVo.setEndDate(DateUtils.addDays(designChangeVo.getEndDate(), 1));
        }
        designChangeVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = designChangeService.selectMyCheckByDomainWhere(page, designChangeVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 设计方案变更-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询设计方案审批通过的记录
        DesignExam designExam = new DesignExam();
        designExam.setProcessStatus("9");
        List<DesignExam> designExams = designExamService.selectByEntityWhere(designExam);
        request.setAttribute("designExams", designExams);
        return "ic/lay-designChange-add";
    }

    /**
     * 根据id查询设计方案变更详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 设计方案变更Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        DesignChangeVo designChangeVo = designChangeService.queryById(id);
        request.setAttribute("modelDetail", designChangeVo);
        map.put("designChangeVo", designChangeVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, designChangeVo.getProcessId());
        return new ModelAndView("ic/lay-designChange-detail", map);
    }

    /**
     * 新增设计方案变更
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(DesignChangeAssist designChangeAssist) {

        //设计方案变更表处理
        designChangeAssist.setHrDeptId(designChangeAssist.getHrDeptid());
        designChangeAssist.setHrOrgId(designChangeAssist.getHrOrgid());
        designChangeAssist.setStaffName(designChangeAssist.getStaffname());
        designChangeAssist.setHrStaffApplyId(designChangeAssist.getHrStaffApplyid());
        String proCodeAndCodes = designChangeAssist.getProCodeAndCodes();
        String[] split = proCodeAndCodes.split("\\_");
        designChangeAssist.setProCode(split[0]);
        designChangeAssist.setProName(split[2]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        designChangeAssist.setId(id);
        designChangeAssist.setAddBy(vo.getId());
        designChangeAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("ic_design_change");
        designChangeAssist.setCodes(code);
        // 处理processId
        designChangeAssist.setProcessId(IdFactory.getUUIDUpper());
        designChangeAssist.setProcessStatus("1");//审批中
        designChangeAssist.setUptBy(vo.getId());
        designChangeAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //明细表
        List<DesignChangeDetail> designChangeDetails = new ArrayList<DesignChangeDetail>();
        //上传附件
        List<DesignChangeAtt> designChangeAtts = new ArrayList<DesignChangeAtt>();
        String[] showIdxDetail = designChangeAssist.getShowIdxDetail();
        if (showIdxDetail != null && showIdxDetail.length > 0) {
            for (int i = 0; i < showIdxDetail.length; i++ ) {
                String showIdx = showIdxDetail[i];
                String itemName = designChangeAssist.getItemNameDetail()[i];
                String unitName = designChangeAssist.getUnitNameDetail()[i];
                String itemNum = designChangeAssist.getItemNumDetail()[i];
                String itemMemo = designChangeAssist.getItemMemoDetail()[i];
                DesignChangeDetail designChangeDetail = new DesignChangeDetail();
                String designChangeDetailId = IdFactory.getUUIDUpper();
                designChangeDetail.setChangeId(id);
                designChangeDetail.setId(designChangeDetailId);
                designChangeDetail.setShowIdx(Integer.parseInt(showIdx));
                designChangeDetail.setItemName(itemName);
                designChangeDetail.setItemNum(new BigDecimal(itemNum));
                designChangeDetail.setUnitName(unitName);
                designChangeDetail.setItemMemo(itemMemo);
                designChangeDetail.setAddBy(vo.getId());
                designChangeDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                designChangeDetails.add(designChangeDetail);
            }

            String[] fileAtts1 = designChangeAssist.getFileAtts1();
            String[] showIdxAtt = designChangeAssist.getShowIdxAtt();
            if (fileAtts1 != null) {
                for (int i = 0; i < fileAtts1.length; i++ ) {
                    DesignChangeAtt designExamAtt = createFileAtt(vo, id, fileAtts1[i]);
                    String showIdx = showIdxAtt[i];
                    designExamAtt.setDetailId(showIdx);
                    designChangeAtts.add(designExamAtt);
                }
            }

            for (DesignChangeAtt designChangeAtt : designChangeAtts) {
                for (DesignChangeDetail designChangeDetail : designChangeDetails) {
                    if (designChangeAtt.getDetailId().equals(
                        String.valueOf(designChangeDetail.getShowIdx()))) {
                        designChangeAtt.setDetailId(designChangeDetail.getId());
                        break;
                    }
                }
            }
            
        }
        designChangeService.saveDesignChange(designChangeAssist, designChangeDetails,
            designChangeAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "投建管理 -设计方案变更：项目名="
                                                              + designChangeAssist.getProName(),
            null);
        return RspVo.getSuccessResponse();
    }

    private DesignChangeAtt createFileAtt(AuthorizationVO vo, String changeId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        DesignChangeAtt fileAtt = new DesignChangeAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setChangeId(changeId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "designChangeAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
